//
//  HomeTableViewController.swift
//  MyNoteDemo4
//
//  Created by BZF on 2020/8/24.
//  Copyright © 2020 bzf. All rights reserved.
//

import UIKit

class HomeTableViewController: UITableViewController {

    private var listData = NSMutableArray()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        NotificationCenter.default.addObserver(self, selector: #selector(reloadView(_:)), name: Notification.Name("reloadListNotification"), object: nil)
        
        loadData()
    }
    
    private func loadData(){
        //        listData = NoteDao.instance.findAll()
        
        NoteRespository.instance.getAll(handler: { response in
            print(response.value)
            do{

                if let nsDictionary  = response.value as? NSDictionary{
                     print("Dictionary",nsDictionary)
                    
                    if let items = nsDictionary.value(forKey: "Record") as? NSArray{
                          self.listData.removeAllObjects()
                        
                        for item in items {
                            let dict = item as? NSDictionary
                            let strDate = dict?.value(forKey: "CDate") as! String
                            
                            let note = Note()
                            let dateFormatter = DateFormatter()
                            dateFormatter.dateFormat = "yyyy-MM-dd"
                        
                            note.date = dateFormatter.date(from: strDate) as! NSDate
                            note.content = dict?.value(forKey: "Content") as! String
                            self.listData.add(note)
                           print("note",note)
                        }
                    }
                }
            }catch{
                print("解析json失败")
            }
            
            DispatchQueue.main.async {
                  self.tableView.reloadData()
            }
        })
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return listData.count
    }

   
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        
        let note = self.listData[indexPath.row] as! Note
        cell.textLabel!.text = note.content
        cell.detailTextLabel!.text = note.date.description
        return cell
    }
   

    // Override to support conditional editing of the table view.
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }


    /*
    // Override to support editing the table view.
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            // Delete the row from the data source
            tableView.deleteRows(at: [indexPath], with: .fade)
        } else if editingStyle == .insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    
    // MARK: - Navigation
    //页面将要跳转时调用
    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "showDetail" {
            if let indexPath = self.tableView.indexPathForSelectedRow {
                let note = self.listData[indexPath.row] as! Note
                
                let controller = (segue.destination as! UINavigationController).topViewController as! DetailViewController
                
                controller.detailItem = note
                controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem
                controller.navigationItem.leftItemsSupplementBackButton = true
            }
        }
    }
    
    
    
    @objc func reloadView(_ notification: Notification) {
        loadData()
    }

}
